package v1

import (
	"fmt"
	"gin_vue_blog/model"
	"gin_vue_blog/utils/errmsg"
	"gin_vue_blog/utils/validator"
	"github.com/gin-gonic/gin"
	"strconv"
)

// 添加文章
func AddArt(c *gin.Context) {
	var data model.Article
	msg, code := validator.Validator(data)
	if code != errmsg.SUCCESS {
		c.JSON(200, gin.H{
			"status": code,
			"msg":    msg,
		})
		return
	}
	_ = c.ShouldBindJSON(&data)
	code = model.CreateArt(&data)
	c.JSON(200, gin.H{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrMsg(code),
	})
}

// 查找分类下所有文章
func GetCateArt(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	cid, _ := strconv.Atoi(c.Query("cid"))
	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	if pageNum == 0 {
		pageNum = 1
	}
	fmt.Println("pageSize:", pageSize, "pageNum:", pageNum, "cid:", cid)
	data, code, total := model.GetCateArtList(pageSize, pageNum, cid)
	c.JSON(200, gin.H{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrMsg(code),
	})
}

// 查询单篇文章
func GetArtInfo(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	fmt.Println("id:", id)
	data, code := model.GetArt(id)
	c.JSON(200, gin.H{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrMsg(code),
	})
}

// 查询文章列表
func GetArtList(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	fmt.Println("pageSize:", pageSize, "pageNum:", pageNum)
	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	if pageNum == 0 {
		pageNum = 1
	}
	data, code, total := model.GetArtList(pageSize, pageNum)
	c.JSON(200, gin.H{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrMsg(code),
	})
}

// 搜索文章标题
func SearchArt(c *gin.Context) {
	title := c.Query("title")
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	data, code, total := model.SearchArt(pageSize, pageNum, title)
	c.JSON(200, gin.H{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrMsg(code),
	})
}

// 更新文章信息
func EditArt(c *gin.Context) {
	var data model.Article
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&data)
	code := model.EditArt(&data, id)
	c.JSON(200, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

// 删除文章
func DeleteArt(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteArt(id)
	c.JSON(200, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}
